﻿using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using vngoodlife.Models;
using System.Web.Routing;
using vngoodlife.Singleton;
using vngoodlife.Util;
using System.IO;
using System.Web.Configuration;
using System.Configuration;
using System.Web.Security;


namespace vngoodlife.Controllers
{
    public class AdminController : Controller
    {
        #region logon
        
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        public ActionResult LogOn()
        {
            if (Request.IsAuthenticated)
            {
                return RedirectToAction("DashBoard", "Admin");
            }
            else
            {
                return View("/Views/Backend/Admin/LogOn.cshtml");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult LogOn(LogOnMemberModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    
                    DataSingleton.Instance.GetMemberModel().UpdateLogInTime(model.UserName);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("DashBoard", "Admin");
                    }
                }
                else
                {
                    //  ModelState.AddModelError("", "The user name or password provided is incorrect."); throw a mesg to view at the Html.ValidationSummary
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            // If we got this far, something failed, redisplay form
            return View("/Views/Backend/Admin/LogOn.cshtml");
        }

        public ActionResult LogOff()
        {
            DataSingleton.Instance.GetMemberModel().UpdateLogOutTime(HttpContext.User.Identity.Name);
            FormsService.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult test()
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Request.Cookies[cookieName];
            ViewBag.time = ConstantClass.authenCookieTimeLife;
            if (authCookie == null)
            {
                ViewBag.note = "ko co cookie";
                return View("/Views/FrontEnd/test.cshtml");
            }
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            


            ViewBag.formname = cookieName;
            ViewBag.user = HttpContext.User.Identity.Name;
            ViewBag.IsAuthenticated = HttpContext.User.Identity.IsAuthenticated;
            ViewBag.role = authTicket.UserData;
            ViewBag.content = authCookie.Value;

            ViewBag.cookiepath = authTicket.CookiePath;
            ViewBag.Expiration = authTicket.Expiration;
            ViewBag.Expired = authTicket.Expired;
            ViewBag.IsPersistent = authTicket.IsPersistent;

            ViewBag.IssueDate = authTicket.IssueDate;
            ViewBag.Name = authTicket.Name;
            ViewBag.UserData = authTicket.UserData;
            




            return View("/Views/FrontEnd/test.cshtml");
        }


        #endregion

        /////////////////////////////////////////////////////////////////////////////////


        #region admin
        [CheckMemberVisibility, Authorize]
        public ActionResult AdminPage()
        {
            return View("/Views/BackEnd/Admin/AdminPage.cshtml");
        }

        /// <summary>
        /// dashboard
        /// </summary>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize(Roles = ConstantClass.admin)]
        public ActionResult DashBoard()
        {
            return View("/Views/BackEnd/Admin/AdminDashBoard.cshtml");
        }

        [CheckMemberVisibility, Authorize(Roles = ConstantClass.superadmin)]
        public ActionResult AdminList_BackEnd()
        {
            return View("/Views/BackEnd/Admin/AdminList.cshtml", DataSingleton.Instance.GetMemberModel().GetAdminList());
        }

        [CheckMemberVisibility, Authorize(Roles = ConstantClass.superadmin)]
        public ActionResult CreateAdmin()
        {
            ViewBag.SexOfAdmin = new SelectList(DataSingleton.Instance.GetGenderModels().GetGenderList().ToList(), "GenderID", "GenderName");
            ViewBag.RoleOfAdmin = new SelectList(DataSingleton.Instance.GetRoleModels().GetRoleOfAdmin().ToList(), "RoleID", "RoleName");
            return View("/Views/BackEnd/Admin/AdminCreate.cshtml");
        }

        [CheckMemberVisibility]
        [HttpPost, Authorize(Roles = ConstantClass.superadmin), ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult CreateAdminSubmit()
        {
            string adminName = HttpContext.User.Identity.Name;
            Member admin = new Member();
            if (ModelState.IsValid && TryUpdateModel(admin))
            {
                if (!DataSingleton.Instance.GetMemberModel().MemberNameIsUsed(admin.MemberName))
                {
                    string pass = DataSingleton.Instance.GetMemberModel().CreateMember(admin, adminName);
                    if (pass != "")
                    {
                        ModelState.AddModelError("NoticePage", "Admin đã tạo với mật khẩu: " + pass);
                    }
                    else
                    {
                        ModelState.AddModelError("NoticePage", "Có lỗi khi tạo Admin. Vui lòng thử lại.");
                    }
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Tên đăng nhập đã có. Vui lòng đổi tên khác.");
                }
            }

            ViewBag.SexOfAdmin = new SelectList(DataSingleton.Instance.GetGenderModels().GetGenderList().ToList(), "GenderID", "GenderName");
            ViewBag.RoleOfAdmin = new SelectList(DataSingleton.Instance.GetRoleModels().GetRoleOfAdmin().ToList(), "RoleID", "RoleName");
            return View("/Views/BackEnd/Admin/AdminCreate.cshtml", admin);
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.superadmin)]
        public ActionResult AdminEdit(string memberName)
        {
            ViewBag.SexOfAdmin = new SelectList(DataSingleton.Instance.GetGenderModels().GetGenderList().ToList(), "GenderID", "GenderName");
            ViewBag.RoleOfAdmin = new SelectList(DataSingleton.Instance.GetRoleModels().GetRoleOfAdmin().ToList(), "RoleID", "RoleName");
            return View("/Views/BackEnd/Admin/AdminEdit.cshtml", DataSingleton.Instance.GetMemberModel().GetMemberDetails(memberName));
        }

        [CheckMemberVisibility]
        [Authorize(Roles = ConstantClass.superadmin), HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult AdminEditSubmit(Member admin, HttpPostedFileBase uploadFile)
        {
            string adminName = HttpContext.User.Identity.Name;
            //Member admin = DataSingleton.Instance.GetMemberModel().GetMemberDetails(memberName);

            if (ModelState.IsValid)
            {
                if (uploadFile != null && uploadFile.ContentLength > 0)
                {
                    //Upload avatar for member
                    admin.Avatar = DataSingleton.Instance.GetGeneralModels()
                                .UploadMemberAvatar(uploadFile, Request.PhysicalApplicationPath.ToString(), admin.MemberName, admin.Avatar);
                }

                if (DataSingleton.Instance.GetMemberModel().EditAdmin(admin, adminName))
                {
                    //Use ModelState.Clear to referesh image file name in hidden field
                    ModelState.Clear();
                    ModelState.AddModelError("NoticePage", "Thông tin của Admin đã được cập nhật.");
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật thông tin admin. Xin vui lòng làm lại.");
                }


            }

            ViewBag.SexOfAdmin = new SelectList(DataSingleton.Instance.GetGenderModels().GetGenderList().ToList(), "GenderID", "GenderName", admin.GenderID);
            ViewBag.RoleOfAdmin = new SelectList(DataSingleton.Instance.GetRoleModels().GetRoleOfAdmin().ToList(), "RoleID", "RoleName", admin.RoleID);
            return View("/Views/BackEnd/Admin/AdminEdit.cshtml", admin);
        }


        [CheckMemberVisibility]
        [Authorize(Roles = ConstantClass.superadmin), HttpPost, ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult RandomPasswordForMember(string memberName)
        {
            string adminName = HttpContext.User.Identity.Name;
            string pass = DataSingleton.Instance.GetMemberModel().RandomPassForMember(memberName, adminName);

            if (pass != "")
            {
                ModelState.AddModelError("NoticePage", "Mật khẩu của " + memberName + " đã được thay đổi là " + pass);
            }
            else
            {
                ModelState.AddModelError("NoticePage", "Có lỗi khi thay đổi mật khẩu cho .");
            }

            Member admin = DataSingleton.Instance.GetMemberModel().GetMemberDetails(memberName);
            ViewBag.SexOfAdmin = new SelectList(DataSingleton.Instance.GetGenderModels().GetGenderList().ToList(), "GenderID", "GenderName", admin.GenderID);
            ViewBag.RoleOfAdmin = new SelectList(DataSingleton.Instance.GetRoleModels().GetRoleOfAdmin().ToList(), "RoleID", "RoleName", admin.RoleID);
            return View("/Views/BackEnd/Admin/AdminEdit.cshtml", admin);
        }


        [CheckMemberVisibility, Authorize]
        public ActionResult ChangeAdminPass()
        {
            string adminName = HttpContext.User.Identity.Name;
            return View("/Views/BackEnd/Admin/ChangeAdminPass.cshtml");
        }


        [CheckMemberVisibility, Authorize, HttpPost]
        public ActionResult ChangeAdminPass(string oldPass, string newPass, string confirmNewPass)
        {
            string adminName = HttpContext.User.Identity.Name;
            if (newPass != "" && newPass.Length >= 6 && newPass == confirmNewPass)
            {
                if (DataSingleton.Instance.GetMemberModel().IsCorrectPassword(adminName, oldPass))
                {
                    if (DataSingleton.Instance.GetMemberModel().ChangePassForMember(adminName, newPass))
                    {
                        ModelState.Clear();
                        ModelState.AddModelError("NoticePage", "Mật khẩu mới đã được cập nhật");
                    }
                    else
                    {
                        ModelState.AddModelError("NoticePage", "Có lỗi khi thay đổi mật khẩu.");
                    }
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Mật khẩu cũ không chính xác.");
                }

            }

            return View("/Views/BackEnd/Admin/ChangeAdminPass.cshtml");
        }

        #endregion
    }
}
